import mitt from 'mitt'

export const renderSearchResult = (text: string, from?: number, to?: number): string => {
  if (from == undefined || to == undefined) {
    return text
  }
  return (
    text.slice(0, from) +
    `<span class="search-hilight">${text.slice(from, to + 1)}</span>` +
    text.slice(to + 1)
  )
}

export const parseRegex = (str: string) => {
  const [, pattern, flags] = /^\/(.*?)\/([gimy]*)$/.exec(str) || []
  return new RegExp(pattern, flags)
}

export const getScrollParent = (node) => {
  if (node == null) {
    return null
  }

  if (node.scrollHeight > node.clientHeight) {
    return node
  } else {
    return getScrollParent(node.parentNode)
  }
}

export const eventBus = mitt()
